package com.webdrider.servlet.action.system;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractValidator;
import com.common.security.errors.ParserError;
import com.common.security.exceptions.ParserException;
import com.common.servlet.abstracts.AbstractParserServlet;
import com.common.servlet.interfaces.IParser;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.webdrider.model.requests.system.CreateChannelRequest;
import com.webdrider.model.response.system.CreateChannelResponse;
import com.webdrider.servlet.util.parser.system.CreateChannelXMLParser;

public class CreateChannelServlet extends AbstractParserServlet {
	private static final long serialVersionUID = 1L;
	private static List<AbstractValidator> validators = new ArrayList<AbstractValidator>();
	
	private CreateChannelRequest requestContent;
	private CreateChannelXMLParser parser = new CreateChannelXMLParser();
	
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response) {
		try {
			CreateChannelResponse createChannelResponse = new CreateChannelResponse();
			ChannelService channelService = ChannelServiceFactory.getChannelService();
			String token = channelService.createChannel(requestContent.getUserToken());
			System.out.println("Token::" + token);
			
			createChannelResponse.setRequestAction(requestContent.getAction());
			createChannelResponse.setToken(token);
			response.setContentType("text/xml");
			response.getWriter().write(parser().parseResponse(createChannelResponse));
			System.out.println("DONE");
			
		} catch (ParserException parserException) {
			exception(parserException, response);
		} catch (IOException ioException) {
			error(new ParserError(ParserError.STREAM_ERROR), response);
		};
	}

	@Override
	public void setRequest(AbstractRequest abstractRequest) {
		requestContent = (CreateChannelRequest) abstractRequest;
	}

	@Override
	public List<AbstractValidator> getValidators() {
		return validators;
	}

	@Override
	public IParser parser() {
		return parser;
	}

}
